package org.czx.datactruct.fifth;

/**
 * @author czx
 * @date 2020/9/5 16:57
 */
public class BalanceChecker {
    /**
     * Decides whether the parentheses, brackets, and braces
     * in a string occur in left/right pairs.
     * 判断左右括号是否平衡
     *
     * @param expression A string to be checked.
     * @return True if the delimiters are paired correctly.
     */
    public static boolean checkBalance(String expression) {
        StackInterface<Character> openDelimiterStack = new OurStack<>();
        int characterCount = expression.length();
        boolean isBalances = true;
        int index = 0;
        char nextCharacter = ' ';
        while (isBalances && index < characterCount) {
            nextCharacter = expression.charAt(index);
            switch (nextCharacter) {
                case '(':
                case '{':
                case '[':
                    openDelimiterStack.push(nextCharacter);
                    break;
                case ']':
                case '}':
                case ')':
                    if (openDelimiterStack.isEmpty())
                        isBalances = false;
                    else {
                        char openDelimiter = openDelimiterStack.pop();
                        isBalances = isPaired(nextCharacter, openDelimiter);
                    }
                    break;
                default:
                    break;
            }
        }
        if (!openDelimiterStack.isEmpty())
            isBalances = false;
        return isBalances;
    }

    /**
     * Returns true if the given characters, open and close, form a pair
     * of parentheses, brackets, or braces.
     */
    private static boolean isPaired(char open, char close) {
        return (open == '(' && close == ')') ||
                (open == '[' && close == ']') ||
                (open == '{' && close == '}');
    }
}
